<template>
  <Dialog
    v-model="dialogVisible"
    :title="titleRef"
    :isModal="false"
    :fullscreen="false"
    width="400px"
  >
    <el-form :model="formData" ref="formRef" :rules="formRules">
      <el-form-item prop="name">
        <el-input ref="nameRef" class="!w-360px" v-model="formData.name" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="MailSignatureNameEdit" lang="ts">
import * as signatureApi from '@/api/mailbox/mailSignature'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)
const formData = ref({
  id: 0,
  name: '',
  content: undefined as undefined | string
})
const formRef = ref()
const nameRef = ref()
const titleRef = ref('重命名')
const emit = defineEmits(['success'])

const formRules = reactive({
  name: [{ required: true, message: '签名名称不能为空', trigger: 'change' }]
})

/** 打开弹窗 */
const open = (params) => {
  dialogVisible.value = true
  formData.value.name = params.name
  formData.value.id = params.id
  if (formData.value.id == 0) {
    titleRef.value = '新建'
  }
  setTimeout(() => {
    nameRef.value.focus()
    nameRef.value.select()
  }, 100)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    if (formData.value.id == 0) {
      formData.value.content = ''
      await signatureApi.createSignature(formData.value)
      message.success(t('common.createSuccess'))
    } else {
      formData.value.content = undefined
      await signatureApi.updateSignature(formData.value)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
  }
}
</script>
